package cn.javadog.ss.spring.ioc.applicationcontext;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author 余勇
 * @date 2019年11月24日 18:39:00
 */
public class ComplexBean implements BeanNameAware, BeanFactoryAware,
	ApplicationContextAware, BeanPostProcessor, InitializingBean, DisposableBean {

	private String param1;
	private String beanName;
	private BeanFactory beanFactory;
	private ApplicationContext applicationContext;

	public ComplexBean() { System.out.println("实例化bean对象"); }

	public void setParam1(String param1) {
		this.param1 = param1;
		System.out.println("设置bean属性");
	}

	@Override
	public void setBeanName(String name) {
		this.beanName = name;
		System.out.println("调用BeanNameAware的setBeanName方法");
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
		System.out.println(String.format("调用BeanFactoryAware的setBeanFactory方法, beanFactory是否为空：[%s]",
			beanFactory == null));
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
		System.out.println(String.format("调用ApplicationContextAware的setApplicationContext方法, " +
			"applicationContext是否为空：[%s]", applicationContext == null));
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("调用BeanPostProcessor的before方法");
		// todo 在这里可以更改bean吗？这里返回值有什么用？
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("调用BeanPostProcessor的after方法");
		return bean;
	}

	public void initMethod(){
		System.out.println("调用init-method方法");
	}

	public void destroyMethod(){
		System.out.println("调用destroy-method方法");
	}

	@Override
	public void destroy() throws Exception {
		System.out.println("调用DisposableBean的destroy方法");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("调用InitializingBean的afterPropertiesSet方法");
	}
}
